package com.haoshuang.zhouzhoubang.ui.page.order.take.code

import android.Manifest
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.Settings
import android.view.View
import android.widget.LinearLayout
import com.blankj.utilcode.util.ToastUtils
import com.gyf.immersionbar.ktx.immersionBar
import com.haoshuang.zhouzhoubang.databinding.ActivityPayCodeBinding
import com.haoshuang.zhouzhoubang.model.bean.TakeOrderPayCodeBean
import com.haoshuang.zhouzhoubang.ui.dialog.Tis2Dialog
import com.haoshuang.zhouzhoubang.utils.PaymentUtil
import com.haoshuang.zhouzhoubang.utils.PermissionHelper
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.SmartGlideImageLoader
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.gone
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visibleOrGone
import java.io.FileNotFoundException
import java.io.IOException
import java.io.OutputStream

/**
 *  用户支付海报
 */
class PayCodeActivity : BaseVMActivity<PayCodeViewModel, ActivityPayCodeBinding>() {

    companion object {
        fun launch(context: Context){
            context.startPage<PayCodeActivity>()
        }
    }

    private var codeBean: TakeOrderPayCodeBean? = null

    // 订单编号
    private val orderSn by lazy {
        intent.getStringExtra("orderSn") ?: ""
    }

    override fun initView(savedInstanceState: Bundle?) {

        binding.tvBack.clickWithTrigger { finish() }
        binding.tvLookPayCode.clickWithTrigger {
            XPopup.Builder(mActivity)
                .asImageViewer(null,codeBean?.scan_pay_code_url, SmartGlideImageLoader())
                .show()
        }
        binding.tvShare.clickWithTrigger {
            // 微信朋友圈分享
            PermissionHelper.requestPermission(
                mActivity,
                "存储权限使用说明",
                "用于快速保存分享图片",
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) {
                if (it) {
                    binding.tvLookPayCode.gone()
                    var bmp = getBitmap(binding.flShareView)
                    addBitmapToAlbum(bmp!!)
                } else {
                    XPopup.Builder(mActivity)
                        .asCustom(Tis2Dialog(mActivity, "开启读写权限是为了保存图片") {
                            val intent = Intent()
                            intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                            intent.data = Uri.parse("package:" + getPackageName())
                            startActivity(intent)

                        })
                        .show()
                }
            }
        }

    }
    private fun getBitmap(view: View): Bitmap? {
        view.isDrawingCacheEnabled = true
        view.buildDrawingCache() //启用DrawingCache并创建位图
        val bitmap =
            Bitmap.createBitmap(view.drawingCache) //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
        view.isDrawingCacheEnabled = false //禁用DrawingCahce否则会影响性能
        return bitmap
    }

    private fun addBitmapToAlbum(bitmap: Bitmap) {
        val displayName = "111jpg"
        val mimeType = "image/jpeg"
        val compressFormat = Bitmap.CompressFormat.JPEG

        val values = ContentValues()
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName)
        values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM)
        }
        val contentResolver = contentResolver
        val uri: Uri? = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        if (uri != null) {
            var outputStream: OutputStream? = null
            try {
                outputStream = contentResolver.openOutputStream(uri)
                bitmap.compress(compressFormat, 100, outputStream)
                outputStream?.close()
                try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        var phth = getFileUri(mActivity, uri)
                        PaymentUtil.wxShareALl2(mActivity, bitmap, false, phth)
                    } else {
                        PaymentUtil.wxShareALl2(
                            mActivity,
                            bitmap,
                            false,
                            uri.path
                        )
                    }

                } catch (e: Exception) {

                }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            if (outputStream != null) {
            }
        }
        binding.tvLookPayCode.visibleOrGone(codeBean?.scan_pay_code_url?.isNotEmpty() == true)
    }
    fun getFileUri(context: Context, contentUri: Uri): String? {
        // 授权给微信访问路径
        context.grantUriPermission(
            "com.tencent.mm",  // 这里填微信包名
            contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
        )
        return contentUri.toString() // contentUri.toString() 即是以"content://"开头的用于共享的路径
    }
    override fun initData() {
        vm.createPayQrcode(orderSn)
    }

    override fun startObserve() {
        vm.createPayQrcodeData.observeState(this){
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                codeBean = it
                binding.apply {
                    tvPayPrice.text = codeBean?.total_pay_price
                    ivCode.load(codeBean?.pay_code_url)
                    rivImage.load(codeBean?.pic)
                    tvServiceName.text = codeBean?.cate_name
                    tvServiceSuk.text = codeBean?.suk_unique
                    tvPrice.text = codeBean?.pay_price
                    tvLookPayCode.visibleOrGone(codeBean?.scan_pay_code_url?.isNotEmpty() == true)
                }
            }
        }
    }
    override fun initImmersionBar() {
        immersionBar {
            transparentStatusBar()
            titleBarMarginTop(binding.flTitleBar)
        }
    }
}